﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.Redis;


namespace YiYiTong.Rocket.Helper
{
    public class RedisPoolManager
    {
        #region Instance

        private PooledRedisClientManager PooledRedisClient
        {
            get;
            set;
        }
        private static RedisPoolManager _instance;

        private static object _syncObject = new object();

        public static RedisPoolManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new RedisPoolManager();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion

        private RedisPoolManager()
        {
            int redisPoolSize = ConfigHelper.AppSetting<int>("RedisServicePoolSize", 200);
            RedisClientManagerConfig RedisConfig = new RedisClientManagerConfig();
            RedisConfig.AutoStart = true;
            RedisConfig.MaxReadPoolSize = redisPoolSize;
            RedisConfig.MaxWritePoolSize = redisPoolSize;
            RedisConfig.DefaultDb = ConfigHelper.AppSetting<int>("RedisServiceDbIndex", 0);

            string ip = ConfigHelper.AppSetting<string>("RedisService", "192.168.8.17");
            int port = ConfigHelper.AppSetting<int>("RedisServicePort", 6379);
            string readWriteHost = ip + ":" + port;
            string readOnlyHost = ip + ":" + port;
            PooledRedisClient = new PooledRedisClientManager(new List<string>() { readWriteHost }, new List<string>() { readOnlyHost }, RedisConfig);
        }

        public IRedisClient GetClient()
        {
            return PooledRedisClient.GetClient();
        }

        public void Dispose(IRedisClient redisClient)
        {
            redisClient.Dispose();
        }
    }
}
